import config
from act import trigger
from act import seeker
from dataDeal.fileUtils import save_to_json


# 根据控件类型找到第一个子控件
def find_control_with_control_type(top_control, control_type):
    children = top_control.GetChildren()
    for child in children:
        if child.ControlTypeName == control_type:
            return child
        result = find_control_with_control_type(child, control_type)
        if result is not None:
            return result
    return None


# 初始化会话，将所有会话设置为已读状态
def init_session(all_session):
    if config.init_sessions_status_dict.get(config.nowtime_str) is not None:
        return
    round_shot = 0
    is_check_all_round = False
    while round_shot <= config.round_time:
        for chat_shot in all_session.GetChildren():
            # 判断是否有消息通知，有则获得消息通知数
            tup = trigger.is_notify_with_text(chat_shot)
            if tup[0]:
                find_control_with_control_type(chat_shot, "ButtonControl").Click()
        if is_check_all_round:
            config.init_sessions_status_dict[config.nowtime_str] = True
            save_to_json(config.init_sessions_status_dict, config.init_sessions_status_dict_file_path)
            break
        round_shot += 1
        if round_shot > config.round_time:
            all_session.WheelUp(wheelTimes=config.round_distance * config.round_time)
            is_check_all_round = True
            round_shot = 0
        else:
            all_session.WheelDown(wheelTimes=config.round_distance)


if __name__ == '__main__':
    weChat_window = seeker.get_window()
    sessions = seeker.get_chat_list_panel(weChat_window)
    file_assistant_button = None
    chat_list = sessions.GetChildren()
    for session in chat_list:
        if session.Name == "文件传输助手已置顶":
            file_assistant_button = session.GetChildren()[0].GetChildren()[0]
            break
    init_session(sessions, file_assistant_button)
